package p2pgame;

import java.io.IOException;
import java.net.InetSocketAddress;

import rice.environment.Environment;
import rice.pastry.NodeHandle;
import rice.pastry.NodeIdFactory;
import rice.pastry.PastryNode;
import rice.pastry.PastryNodeFactory;
import rice.pastry.socket.SocketPastryNodeFactory;
import rice.pastry.standard.RandomNodeIdFactory;

public class BasicSocket {


	protected NodeIdFactory nidFactory;
	protected PastryNodeFactory factory;
	protected NodeHandle bootHandle;
	protected PastryNode node;

	public BasicSocket(int bindport, InetSocketAddress bootaddress, Environment env) throws Exception {

		nidFactory = new RandomNodeIdFactory(env);
		factory = new SocketPastryNodeFactory(nidFactory, bindport, env);
		bootHandle = ((SocketPastryNodeFactory)factory).getNodeHandle(bootaddress);
		node = factory.newNode(bootHandle);
		// the node may require sending several messages to fully boot into the ring
		synchronized(node) {
			while(!node.isReady() && !node.joinFailed()) {
				// delay so we don't busy-wait
				node.wait(500);

				// abort if can't join
				if (node.joinFailed()) {
					throw new IOException("Could not join the FreePastry ring.  Reason:"+node.joinFailedReason()); 
				}
			}       
		}

		System.out.println("Finished creating new node "+node);

	}
}
